package org.example.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.mail.MailUtil;
import org.example.constant.Constant;
import org.example.dto.ChartInformationDto;
import org.example.dto.PersonalInfoDto;
import org.example.vo.PersonalInfoVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.function.DoubleToIntFunction;

/**
 * 注意：username就是学号/教工号！！！
 *
 * @author Rongchang Wu
 */

@Controller
//@RequestMapping("/admin")
public class CommonController {

    /**
     * 登入
     *
     * @param username 学号/教工号
     * @param password 密码
     * @param session
     * @return 登入状态
     */
    @PostMapping(value = "/login", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String login(String username, String password, HttpSession session) {
        System.out.println("进入LoginController的login方法");
        if ("admin".equals(username) && "admin".equals(password)) {//转到service判断
            session.setAttribute("username", username);
            //调用service根据username获取name,赋值给name
            String name = "吴荣昌";
            session.setAttribute("name", name);
            return "success";
        }
        return "error";
    }

    /**
     * 注销
     *
     * @param session
     * @return 登入界面
     */
    @RequestMapping("/logout")
    public ModelAndView logout(HttpSession session) {
        Object username = session.getAttribute("username");
        ModelAndView mv = new ModelAndView();
        if (username != null) {
            session.removeAttribute("username");
            session.removeAttribute("name");
        }
        mv.setViewName("redirect:/index.jsp");
        return mv;
    }

    /**
     * 获取名字
     *
     * @param session
     * @return 名字
     */
    @GetMapping(value = "/getName", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String getName(HttpSession session) {
        return (String) session.getAttribute("name");
    }

    /**
     * 获取飞人信息
     *
     * @param session
     * @return 个人信息dto
     */
    @GetMapping("/getPersonalInfo")
    @ResponseBody
    public PersonalInfoDto getPersonalInfo(HttpSession session) {
        Object obj = session.getAttribute("username");
        String username = null;
        if (obj != null) {
            username = (String) obj;
        }

        PersonalInfoDto personalInfo = new PersonalInfoDto();
        personalInfo.setId("1912120435");
        personalInfo.setName("吴荣昌");
        personalInfo.setPhone("17605054549");
        personalInfo.setBirthday("2001-05-10");
        personalInfo.setPosition("助教");
        personalInfo.setEmail("1971314652@qq.com");
        personalInfo.setProvince("福建省");
        personalInfo.setCity("厦门市");
        personalInfo.setDistrict("集美区");
        personalInfo.setAddress("理工路600号厦门理工学院");
        //根据username查找对应信息，返回personalInfo

        return personalInfo;
    }

    /**
     * 更新个人信息
     *
     * @param PersonalInfo 个人信息vo
     * @return 修改状态
     */
    @PostMapping(value = "/updatePersonalInfo", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String updatePersonalInfo(PersonalInfoVo PersonalInfo) {
        System.out.println(PersonalInfo);
        //执行service修改数据库的个人信息，返回一个状态值赋值给status
        Integer status = 1;

        return status > 0 ? "success" : "error";
    }

    /**
     * 随机生成验证码
     *
     * @param n 生成验证码个数
     * @return 验证码
     */
    private String randomStr(int n) {
        String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        String str2 = "";
        int len = str1.length() - 1;
        double r;
        for (int i = 0; i < n; i++) {
            r = (Math.random()) * len;
            str2 = str2 + str1.charAt((int) r);
        }
        return str2;
    }

    /**
     * 修改密码
     *
     * @param newPassword 新密码
     * @return 修改密码状态
     */
    @PostMapping(value = "/updatePassword", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String updatePassword(String newPassword) {
        //执行service修改数据库的密码，返回一个状态值赋值给status
        Integer status = 1;

        return status > 0 ? "success" : "error";
    }

    @GetMapping(value = "/getChartInfo")
    @ResponseBody
    public ChartInformationDto getChartInfo(){
        ChartInformationDto chartInformation = new ChartInformationDto();
        chartInformation.setBuildingNumber(34);
        chartInformation.setClassNumber(78);
        chartInformation.setClassroomNumber(124);
        chartInformation.setNewStudentNumber(245);
        chartInformation.setNewTeacherNumber(23);
        chartInformation.setStudentNumber(117);
        chartInformation.setTeacherNumber(131);
        //以上从service获取信息

        return chartInformation;
    }

    /**
     * 找回密码
     *
     * @param username     学号/教工号
     * @param verification 验证码
     * @return 状态结果
     */
    @PostMapping(value = "/retrievePassword", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String retrievePassword(String username, String verification) {
        Date endDate = DateUtil.date();
        long between = DateUtil.between(this.startDate, endDate, DateUnit.MINUTE);
        //验证码失效
        if (between >= Constant.VERIFICATION_CODE_EXPIRATION_TIME) {
            return "expirationTime";
        }
        if (this.isUse) {
            return "verificationCodeIsUsed";
        }

        Integer status = 1;
        if (this.verification.equals(verification) && !this.isUse) {
            this.isUse = true;
            //调用service重置密码，返回状态给status
        } else {
            status = -1;
        }

        if (status > 0) {
            return "success";
        } else if (status == -1) {
            return "verificationError";
        }
        return "error";
    }

    private String verification;
    private String username;
    private Date startDate;
    private boolean isUse;

    /**
     * @param email    绑定的邮箱
     * @param username 学号/教工号
     * @return 邮件发送状态
     */
    @PostMapping(value = "/verification", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String verification(String email, String username) {
        String verification = randomStr(Constant.NUMBER_OF_VERIFICATION_CODE);
        System.out.println("验证码为 = " + verification);
        this.verification = verification;
        this.username = username;
        this.isUse = false;
        String content = "<table style=\"margin: 0 auto\" width=\"60%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "\n" +
                "        <tbody>\n" +
                "            <tr>\n" +
                "                <td class=\"p-80 mpy-35 mpx-15\" bgcolor=\"#212429\" style=\"padding: 80px;\">\n" +
                "                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "\n" +
                "\n" +
                "                        <tbody>\n" +
                "                            <tr>\n" +
                "                                <td class=\"img pb-45\"\n" +
                "                                    style=\"font-size:0pt; line-height:0pt; text-align:left; padding-bottom: 45px;\">\n" +
                "                                    <a href=\"http://localhost:8080/index.jsp\" target=\"_blank\" rel=\"noopener\">\n" +
                "                                        <img src=\"https://s2.loli.net/2021/12/06/KXGtZHY9iwWaSg5.png\"\n" +
                "                                            width=\"969\" height=\"217\" border=\"0\">\n" +
                "                                    </a>\n" +
                "\n" +
                "                                </td>\n" +
                "                            </tr>\n" +
                "\n" +
                "\n" +
                "\n" +
                "                            <tr>\n" +
                "                                <td>\n" +
                "\n" +
                "                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                        <tbody>\n" +
                "                                            <tr>\n" +
                "                                                <td class=\"title-36 pb-30 c-grey6 fw-b\"\n" +
                "                                                    style=\"font-size:36px; line-height:42px; font-family:'Motiva Sans', Helvetica, Arial, sans-serif; text-align:left; padding-bottom: 30px; color:#bfbfbf; font-weight:bold;\">\n" +
                "                                                    " + this.username + "，您好！</td>\n" +
                "                                            </tr>\n" +
                "                                        </tbody>\n" +
                "                                    </table>\n" +
                "                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                        <tbody>\n" +
                "                                            <tr>\n" +
                "                                                <td class=\"text-18 c-grey4 pb-30\"\n" +
                "                                                    style=\"font-size:18px; line-height:25px; font-family:'Motiva Sans', Helvetica, Arial, sans-serif; text-align:left; color:#dbdbdb; padding-bottom: 30px;\">\n" +
                "                                                    您的帐户 " + this.username + " 所需的验证码 为【验证码三分钟有效！】：</td>\n" +
                "                                            </tr>\n" +
                "                                        </tbody>\n" +
                "                                    </table>\n" +
                "                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                        <tbody>\n" +
                "                                            <tr>\n" +
                "                                                <td class=\"pb-70 mpb-50\" style=\"padding-bottom: 70px;\">\n" +
                "                                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"\n" +
                "                                                        bgcolor=\"#17191c\">\n" +
                "                                                        <tbody>\n" +
                "                                                            <tr>\n" +
                "                                                                <td class=\"py-30 px-56\"\n" +
                "                                                                    style=\"padding-top: 30px; padding-bottom: 30px; padding-left: 56px; padding-right: 56px;\">\n" +
                "                                                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\"\n" +
                "                                                                        cellpadding=\"0\">\n" +
                "                                                                        <tbody>\n" +
                "                                                                            <tr>\n" +
                "                                                                                <td class=\"title-48 c-blue1 fw-b a-center\"\n" +
                "                                                                                    style=\"font-size:48px; line-height:52px; font-family:'Motiva Sans', Helvetica, Arial, sans-serif; color:#3a9aed; font-weight:bold; text-align:center;\">\n" +
                "                                                                                    " + this.verification + " </td>\n" +
                "                                                                            </tr>\n" +
                "                                                                        </tbody>\n" +
                "                                                                    </table>\n" +
                "                                                                </td>\n" +
                "                                                            </tr>\n" +
                "                                                        </tbody>\n" +
                "                                                    </table>\n" +
                "                                                </td>\n" +
                "                                            </tr>\n" +
                "                                        </tbody>\n" +
                "                                    </table>\n" +
                "                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                        <tbody>\n" +
                "                                            <tr>\n" +
                "                                                <td class=\"text-18 c-grey4 pb-30\"\n" +
                "                                                    style=\"font-size:18px; line-height:25px; font-family:'Motiva Sans', Helvetica, Arial, sans-serif; text-align:left; color:#dbdbdb; padding-bottom: 30px;\">\n" +
                "                                                    您会收到这封自动产生的邮件，是由于您正在找回密码。<br><br>\n" +
                "                                                    Dream 令牌验证码是完成找回密码所必需的。\n" +
                "                                                </td>\n" +
                "                                            </tr>\n" +
                "                                        </tbody>\n" +
                "                                    </table>\n" +
                "                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                        <tbody>\n" +
                "                                            <tr>\n" +
                "                                                <td class=\"text-18 c-blue1 pb-40\"\n" +
                "                                                    style=\"font-size:18px; line-height:25px; font-family:'Motiva Sans', Helvetica, Arial, sans-serif; text-align:left; color:#3a9aed; padding-bottom: 40px;\">\n" +
                "                                                </td>\n" +
                "                                            </tr>\n" +
                "                                        </tbody>\n" +
                "                                    </table>\n" +
                "\n" +
                "\n" +
                "                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                        <tbody>\n" +
                "                                            <tr>\n" +
                "                                                <td class=\"pt-30\" style=\"padding-top: 30px;\">\n" +
                "                                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n" +
                "                                                        <tbody>\n" +
                "                                                            <tr>\n" +
                "                                                                <td class=\"img\" width=\"3\" bgcolor=\"#3a9aed\"\n" +
                "                                                                    style=\"font-size:0pt; line-height:0pt; text-align:left;\">\n" +
                "                                                                </td>\n" +
                "                                                                <td class=\"img\" width=\"37\"\n" +
                "                                                                    style=\"font-size:0pt; line-height:0pt; text-align:left;\">\n" +
                "                                                                </td>\n" +
                "                                                                <td>\n" +
                "                                                                    <table width=\"100%\" border=\"0\" cellspacing=\"0\"\n" +
                "                                                                        cellpadding=\"0\">\n" +
                "                                                                        <tbody>\n" +
                "                                                                            <tr>\n" +
                "                                                                                <td class=\"text-16 py-20 c-grey4 fallback-font\"\n" +
                "                                                                                    style=\"font-size:16px; line-height:22px; font-family:'Motiva Sans', Helvetica, Arial, sans-serif; text-align:left; padding-top: 20px; padding-bottom: 20px; color:#f1f1f1;\">\n" +
                "                                                                                    祝您愉快，<br>\n" +
                "                                                                                    Dream团队 </td>\n" +
                "                                                                            </tr>\n" +
                "                                                                        </tbody>\n" +
                "                                                                    </table>\n" +
                "                                                                </td>\n" +
                "                                                            </tr>\n" +
                "                                                        </tbody>\n" +
                "                                                    </table>\n" +
                "                                                </td>\n" +
                "                                            </tr>\n" +
                "                                        </tbody>\n" +
                "                                    </table>\n" +
                "\n" +
                "\n" +
                "                                </td>\n" +
                "                            </tr>\n" +
                "\n" +
                "                        </tbody>\n" +
                "                    </table>\n" +
                "                </td>\n" +
                "            </tr>\n" +
                "\n" +
                "\n" +
                "\n" +
                "\n" +
                "\n" +
                "        </tbody>\n" +
                "    </table>";
        try {
            MailUtil.send(email, "找回密码", content, true);
            this.startDate = DateUtil.date();
        } catch (Exception e) {
            //邮件发送失败，返回error
            return "error";
        }
        return "success";
    }


}
